var http = require('http');
var crypto = require('crypto');

function Client (keys) {
    this.api_key = keys.api;
    this.secret_key = keys.secret;
    this.timestap = new Date().getTime().toString();

    this.signStr = this._getSignStr();
    this.jsonStr = this._getJsonStr();
    this.authorization = this._getAuthorization();

    this.reqOptions = {
        host: 'open.home.komect.com',
        path: '/api/v1/sms/send',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': this.authorization,
        }
    };
}

Client.prototype._getSignStr = function () {
    var hash = crypto.createHash('md5');

    hash.update(this.api_key);
    hash.update(this.secret_key);
    hash.update(this.timestap);

    return hash.digest('hex');
};

Client.prototype._getJsonStr = function () {
    return JSON.stringify({
        'apiKey': this.api_key,
        'time': this.timestap,
        'sign': this.signStr
    });
};

Client.prototype._getAuthorization = function () {
    return Buffer.from(this.jsonStr).toString('base64');
};

Client.prototype.send = function (options, callback) {
    var parameterObj = {};
    for (var i = 0; i < options.parameters.length; i++) {
        parameterObj['param' + (i+1)] = options.parameters[i];
    }

    var reqBody = JSON.stringify({
        'messageSign': options.sign,
        'mobile': options.mobile,
        'needReceipt': 0,
        'templateId': options.id,
        'templateParameter': parameterObj
    });

    var request = http.request(this.reqOptions, function (response) {
        response.setEncoding('utf-8');
        response.on('data', function (data) {
            if (response.statusCode !== 200) {
                callback(new Error(data.toString()));
            } else {
                callback(undefined);
            }
        });
    });

    request.end(reqBody);
};

exports.Client = Client;
